<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" :request-api="getTableList">
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button type="primary" :icon="CirclePlus" @click="openDrawer('新增')">新增AI Chat 对话</el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
        <el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)">编辑</el-button>
        <el-button type="danger" link :icon="Delete" @click="handleDelete(scope.row.id)">删除</el-button>
      </template>
    </ProTable>
    <ChatDrawer ref="drawerRef" />
  </div>
</template>

<script setup lang="tsx" name="chatManage">
import { ref, reactive } from "vue";
import ProTable from "@/components/ProTable/index.vue";
import ChatDrawer from "./detail.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, View } from "@element-plus/icons-vue";
import { useMessage } from "@/hooks/useMessage";
import { getChatPage, Chat, createChat, updateChat, deleteChat, getChat } from "@/api/ai/chat";
const message = useMessage();
// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  return getChatPage(params);
};

// 表格配置项
const columns = reactive<ColumnProps<Chat.ResChat>[]>([
  { prop: "userId", label: "用户Id" },
  { prop: "title", label: "对话标题" },
  { prop: "pinned", label: "是否置顶" },
  { prop: "pinnedTime", label: "置顶时间" },
  { prop: "roleId", label: "角色id" },
  { prop: "knowledgeId", label: "知识库id" },
  { prop: "modelId", label: "模型id" },
  { prop: "systemMessage", label: "角色设定" },
  { prop: "temperature", label: "温度参数" },
  { prop: "maxTokens", label: "单条回复的最大 Token 数量" },
  { prop: "maxContexts", label: "上下文的最大 Message 数量" },
  { prop: "createTime", label: "创建时间" },
  { prop: "operation", label: "操作", fixed: "right", width: 330 }
]);

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof ChatDrawer> | null>(null);

/**
 * 删除按钮操作
 * @param id
 */
const handleDelete = async (id: number) => {
  await message.delConfirm();
  await deleteChat(id);
  message.success("删除成功");
  proTable.value.getTableList();
};
const openDrawer = async (title: string, row: Partial<Chat.ResChat> = {}) => {
  if (row?.id) {
    const res = await getChat(row.id);
    row = res.data;
  }
  const params = {
    title,
    isView: title === "查看",
    row: { ...row },
    api: title === "新增" ? createChat : title === "编辑" ? updateChat : undefined,
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value?.acceptParams(params);
};
</script>
